/**
 * 
 */
package dbAccess;

import java.sql.*;
import java.util.ArrayList;

import exceptions.*;

import model.Professeur;

/**
 * @author Anthares & Hennek
 *
 */
public class ProfesseurDBAccess {
	public ArrayList<Professeur> getAllProfesseur() throws PasIdentificationException, DatabaseErrorException{
		ArrayList<Professeur> tabProf = new ArrayList<Professeur>();
		Connection conn = DBConnexionSingleton.getInstance();
		PreparedStatement stat;
		String query = "select * from professeur;";
		try {
			stat = conn.prepareStatement(query);
			ResultSet data = stat.executeQuery();
			while(data.next()){
				Professeur p = new Professeur(data.getInt("professeur_id"), data.getString("nom"), data.getString("prenom"));
				tabProf.add(p);
			}
			stat.close();
		} catch (SQLException e) {
			throw new DatabaseErrorException(e);
		}
		return tabProf;
	}
	public Professeur getProfesseur(int professeur_id) throws PasIdentificationException, DatabaseErrorException{
		Professeur prof = null;
		Connection conn = DBConnexionSingleton.getInstance();
		PreparedStatement stat;
		String query = "select * from professeur where professeur_id = ?;";
		try {
			stat = conn.prepareStatement(query);
				stat.setInt(1, professeur_id);
			ResultSet data = stat.executeQuery();
			while(data.next()){
				prof = new Professeur(data.getInt("professeur_id"), data.getString("nom"), data.getString("prenom"));
			}
			stat.close();
		} catch (SQLException e) {
			throw new DatabaseErrorException(e);
		}
		return prof;
	}
	public int addProfesseur(Professeur p) throws PasIdentificationException, DatabaseErrorException{
		Connection conn = DBConnexionSingleton.getInstance();
		int prof_id = -1;
		PreparedStatement stat;
		String query;
		try {
			query = "select max(professeur_id) from professeur;";
			stat = conn.prepareStatement(query);
			ResultSet data = stat.executeQuery();
			while(data.next()){
				prof_id = data.getInt(1);
			}
			stat.close();
			prof_id++;
			
			query = "insert into professeur (nom, prenom) values (?,?);";
			stat = conn.prepareStatement(query);
				stat.setString(1, p.getNom());
				stat.setString(2, p.getPrenom());
			stat.executeUpdate();
			stat.close();
			conn.commit();
		} catch (SQLException e) {
			throw new DatabaseErrorException(e);
		}
		return prof_id;
	}
}
